package com.lsy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsy.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名：springboot01
 * 包名：com.lsy.service
 * 类名：CustomUserDetailsService
 * 描述：
 * 作者：柳胜酉
 * 开始时间：2023/6/12
 * 完成时间：
 * 版本：1.0
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //使用mybatis-plus从数据库读取用户信息
        LambdaQueryWrapper<com.lsy.entity.User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(com.lsy.entity.User::getUsername, username);
        com.lsy.entity.User user = userMapper.selectOne(wrapper);
        //将用户信息封装成User返回
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        } else {
            List<GrantedAuthority> list = new ArrayList<>();
            list.add(new SimpleGrantedAuthority("ROLE_" + user.getRoleId()));
            User u = new User(user.getUsername(), user.getPassword(), list);
            return u;
        }
    }
}


